<?php
 /**
  * oa-hr导入用户信息
  * **/
apf_require_class('Oa_Job_Attendance_Abstract');
class Oa_Job_Attendance_OaHrSynergyData extends Oa_Job_Attendance_Abstract {

    /** 数据库读 **/
    private $readdb = 'hroa_master';

    /** 数据库写 **/
    private $writedb = 'hroa_master';

    /** oa表 **/
    private $oa_readdb = 'attendance_slave';

    /** 金蝶数据库读 **/
    private $kdreaddb = 'kd_slave';

    /**
     * 用户信息,id code superior_code
     */
    private $user_ids;

    private static $dismission;

    private $filter_time = 1354204800;

    private $citie = array();

    public function run($params) {
        ini_set("memory_limit",'512M');
        $start = microtime(true);
        $this->log("开始执行啦！");
        $this->db_connect();
        //获得城市
        $this->citie = $this->_get_cities();
        //同步人员信息
        //$this->syn_userinfo_data();
        //$this->insert_no_code_user();

        if('update' == $params) {
            $this->update_syn_userinfo_data();
        }

        $this->log ( "开始..." );
        //导出金蝶里面坏的部门数据
        //$this->import_bad_department_info();
        $end = microtime(true) - $start;
        $this->log("共耗时:".$end);
        $this->log("job执行结束！");
    }

    private function _get_cities() {
        $result = array();
        $s_sql = "select * from city";
        $rs = $this->get_db_rows($s_sql, $this->readdb);
        if(empty($rs)) {
            return $result;
        }

        foreach($rs as $v) {
            $result[$v['city_id']] = $v['city_name'];
            $result[trim($v['city_name'])] = $v['city_id'];
        }
        return $result;
    }

    private function _get_user_info() {
        $s_sql = "select user_code,user_id from user";
        $oa_userinfo_data = $this->get_db_rows_assoc($s_sql, $this->readdb);
        return $oa_userinfo_data;
    }

    public function get_origin_user_info() {
        $s_sql = "select code as user_code,user_id,job_status,dimission_date from user_info";
        $orgin_oa_userinfo_data = $this->get_db_rows_assoc($s_sql, $this->oa_readdb);
        return $orgin_oa_userinfo_data;
    }

    //zhidong update同步人员信息
    public function update_syn_userinfo_data() {
        $s_sql = "select
                  empl.EM_ID,empl.Name,empl.Code,empla.HRMS_UserField_1,empl.EMail,empl.Sex,empl.Telphone,empl.Mobile,empla.FEnglishName,
                  hminfo.EnterGroupDate,hminfo.InDueDate,empl.DimissionTime,empl.Status as onornot,hminfo.ProbationTerm,
                  empo.PositionName,empo.JobName,empo.UnitID,empo.UnitName,empo.BusinessGroupName,empo.CompanyName,empo.ServicePeriod,empo.EmployeeType,
                  emdi.Status,emdi.EnterDate,emdi.InDueDate,emdi.JobClassName,emdi.JobGrade,emdi.CompanyCode,emdi.DimissionType,emdi.FireType,
                  empl.IDCardID,empl.PastportNum,empl.Birthday,empl.NativePlace,empl.IDAddress,empl.NowWorkSpeciality,empl.MarriedStatus,empl.BankName,empl.BankAccountNum,
                  empla.NowResidence,
                  dinfo.Reason,
                  emcon.BeginDate,emcon.EndDate
                  from HM_Employees as empl
                  left join HM_EmployeesAddInfo as empla on empl.EM_ID=empla.EM_ID
                  left join HM_Em_WorkInfo as hminfo on empl.EM_ID = hminfo.EM_ID
                  left join v_Report_Workinfo as empo on empl.EM_ID = empo.EM_ID
                  left join v_Report_EmployeeDetailInfo as emdi on empl.EM_ID = emdi.EM_ID
                  left join V_Report_DimissionUnionFireInfo as dinfo on empl.EM_ID = dinfo.EM_ID
                  left join HM_EM_Contracts as emcon on empl.EM_ID = emcon.EM_ID";
        $result = mssql_query($s_sql);
        $data = array();
        $time = time();
        $is_have_list = array();//一个人有多个重复的离职信息，所以需要过滤
        while( $row = mssql_fetch_assoc($result) ) {
            if(in_array($row['Code'],$is_have_list)) {continue;}
            $rs['user_type']    = $this->_get_user_type($this->set_utf8($row['EmployeeType'])); //1:试用员工,2:正式员工，3:实习生，4:兼职,5:临时工
            $rs['indue_date'] = $this->_get_date($row['InDueDate']);//转正时间
            $rs['join_start'] = $this->_get_date($row['BeginDate']);//合同开始时间
            $rs['join_end'] = $this->_get_date($row['EndDate']);//合同结束时间
            $this->log("xiugai新增");
            $where['user_code'] =  $row['Code'];
            $is_have_list[] = $row['Code'];
            $this->_update_data($rs,$where);
            }
            return true;
    }

    //同步人员信息
    public function syn_userinfo_data() {
        $orgin_oa_userinfo_data = $this->get_origin_user_info();
        $s_sql = "select
                  empl.EM_ID,empl.Name,empl.Code,empla.HRMS_UserField_1,empl.EMail,empl.Sex,empl.Telphone,empl.Mobile,empla.FEnglishName,
                  hminfo.EnterGroupDate,hminfo.InDueDate,empl.DimissionTime,empl.Status as onornot,hminfo.ProbationTerm,
                  empo.PositionName,empo.JobName,empo.UnitID,empo.UnitName,empo.BusinessGroupName,empo.CompanyName,empo.ServicePeriod,empo.EmployeeType,
                  emdi.Status,emdi.EnterDate,emdi.InDueDate,emdi.JobClassName,emdi.JobGrade,emdi.CompanyCode,emdi.DimissionType,emdi.FireType,
                  empl.IDCardID,empl.PastportNum,empl.Birthday,empl.NativePlace,empl.IDAddress,empl.NowWorkSpeciality,empl.MarriedStatus,empl.BankName,empl.BankAccountNum,
                  empla.NowResidence,
                  dinfo.Reason,
                  emcon.BeginDate,emcon.EndDate
                  from HM_Employees as empl
                  left join HM_EmployeesAddInfo as empla on empl.EM_ID=empla.EM_ID
                  left join HM_Em_WorkInfo as hminfo on empl.EM_ID = hminfo.EM_ID
                  left join v_Report_Workinfo as empo on empl.EM_ID = empo.EM_ID
                  left join v_Report_EmployeeDetailInfo as emdi on empl.EM_ID = emdi.EM_ID
                  left join V_Report_DimissionUnionFireInfo as dinfo on empl.EM_ID = dinfo.EM_ID
                  left join HM_EM_Contracts as emcon on empl.EM_ID = emcon.EM_ID";
        $result = mssql_query($s_sql);
        $data = array();
        $time = time();
        $is_have_list = array();//一个人有多个重复的离职信息，所以需要过滤
        while( $row = mssql_fetch_assoc($result) ) {
            if(in_array($row['Code'],$is_have_list)) {continue;}
            $_in_time = trim($row['EnterGroupDate']);
            $_in_time = strtotime($_in_time);
            if($_in_time >= $this->filter_time) {continue;}
            //if($this->set_utf8($row['Status']) == "离职") {continue;}
            $is_have_list[] = $row['Code'];
            $rs = array();
            //$rs['kd_em_id'] = mssql_guid_string($row['EM_ID']);
            $rs['user_id'] = $orgin_oa_userinfo_data[$row['Code']]['user_id'];
            if(empty($rs['user_id']) || empty($row['Code'])) {continue;}
            $rs['user_name'] = $this->set_utf8($row['Name']);
            $rs['real_name'] = $this->set_utf8($row['Name']);
            $rs['sex']       = $row['Sex'];
            $rs['identity_code'] = $this->_get_idcard_id($row['IDCardID'],$row['PastportNum']);//身份证或护照
            $rs['identity_type'] = $this->_get_idcard_type($row['IDCardID'],$row['PastportNum']);//身份证或护照类型 1:身份证；2：护照
            $rs['birthday'] = $this->_get_date($row['Birthday']);//获得生日  19601011
            $rs['native_place'] = $this->set_utf8($row['NativePlace']);//籍贯
            $rs['identity_address'] = $this->set_utf8($row['IDAddress']);//身份证地址
            $rs['present_address'] = $this->set_utf8($row['NowResidence']);//现居地址
            $rs['degree'] = $this->_get_degree_id($this->set_utf8($row['NowWorkSpeciality'])); //学位
            $rs['graduate_time'] = ""; //毕业时间
            $rs['graduate_university'] = ""; //毕业院校
            $rs['profession'] = ""; //专业
            $rs['marital_status'] = $this->set_utf8($row['MarriedStatus']); //婚姻状态 1:未婚 2：已婚
            $rs['fertility_status'] = "";// 1:未生育 2：已生育
            $rs['english_name'] = $row['FEnglishName'];
            $rs['office_phone'] = $this->_get_phone($row['HRMS_UserField_1']);//公司电话号码
            $rs['office_phone_ex'] = $this->_get_phone_ex($row['HRMS_UserField_1']);//电话及分机号
            $rs['cellphone'] = empty($row['Mobile']) ? "0":$row['Mobile'];//手机
            $rs['office_mail'] = empty($row['EMail']) ? "0":$row['EMail'];//邮箱
            $rs['emergency_people'] = "";//紧急联系人
            $rs['emergency_phone'] = "";//紧急联系电话
            $rs['company_id'] = $this->_get_company_id($row['CompanyCode']);//签约公司

            $rs['city_id']    = $this->_get_city_id($this->set_utf8($row['CompanyName']));//签约城市ID
            $rs['work_city_id'] = $this->_get_city_id($this->set_utf8($row['CompanyName']));//工作城市ID
            $rs['user_code']    = $row['Code'];
            $rs['user_type']    = $this->_get_user_type($this->set_utf8($row['EmployeeType'])); //1:试用期员工,2:正式员工，3:实习生，4:兼职,5:临时工
            $rs['job_status']   = $this->_get_job_status($orgin_oa_userinfo_data[$row['Code']]['job_status'],$orgin_oa_userinfo_data[$row['Code']]['dimission_date']);//1:在职，2：离职
            $rs['leaving_type'] = $this->_get_leaving_type($this->set_utf8($row['DimissionType']),$this->set_utf8($row['FireType']));
            $rs['reason_id'] = "";//金蝶的离职原因与现在的不符，故留空
            $rs['other_reason'] = "";//其他离职原因
            $rs['enter_date'] = $this->_get_date($row['EnterGroupDate']); //入职时间
            $rs['indue_date'] = $this->_get_date($row['InDueDate']);//转正时间
            $rs['leaving_date'] = $this->get_dimissionTime($row['onornot'],$row['DimissionTime']);//离职时间
            $rs['last_date'] = $this->get_dimissionTime($row['onornot'],$row['DimissionTime']);//最后工作日
            $rs['join_start'] = $this->_get_date($row['BeginDate']);//合同开始时间
            $rs['join_end'] = $this->_get_date($row['EndDate']);//合同结束时间
            $rs['join_keep'] = $this->_get_join_keep($row['BeginDate'],$row['EndDate']);//合同年限

            $rs['trial_start'] = $this->_get_date($row['EnterGroupDate']);//试用期开始时间
            $rs['trial_end']   = $this->_get_date($row['InDueDate']);//试用期结束时间
            $rs['trial_keep']  = $row['ProbationTerm'];//试用期

            $rs['bank_name']   = $this->set_utf8($row['BankName']);
            $rs['bank_card']   = $row['BankAccountNum'];
            $rs['p_level']   = $this->_get_p_level($row['JobClassName'],$row['JobGrade'],"P"); //获得p级
            $rs['m_level']   = $this->_get_p_level($row['JobClassName'],$row['JobGrade'],"M"); //获得m级
            $rs['new_train']   = "1";  //新员工是否培训
            $rs['created']   = $time; //创建时间

//             if(isset($oa_userinfo_data[$rs['user_code']])) {
//                 $this->log("同步");
//                 unset($rs['created']);
//                 unset($rs['user_code']);
//                 var_dump($this->_update_data($rs,array('user_code'=>$row['Code'])));
//             }else {
                $this->log("新增");
                var_dump($this->_insert_data($rs));
            //}
        }

        $this->insert_no_code_user();

        return true;
    }

    public function add_user_list() {
        /*
        |    7741 | 廖麒麟 | SHS374 |
        |    7732 | 杜一凡 | SHS377 |
        |    7740 | 费培培 | SHS378 |
        |    7736 | 倪佳    | SHS380 |
        |    7739 | 张其炯 | SHS381 |
        |    7737 | 张禄旭 | SHS382 |
        |    7730 | 高科    | SHS385 |
        |    7733 | 袁壮    | SHS387 |
        |    7731 | 肖云龙 | SHS389 |
        |    7734 | 王明永 | SHS392 |
        |    7725 | 任静    | SHS394 |
        |    7727 | 宋唯娜 | SHS395 |
        |    7728 | 黄丹    | SHS396 |
        |    7726 | 赵宇昕 | SHS397 |
        |    7724 | 龙礡涛 | SHS398 |
        |    7766 | 杨玲蕴 | SHS399 |
        |    7750 | 王夷白 | SHS401 |
        |    7743 | 王祥    | SHS404 |
        |    7749 | 郝春霞 | SHS406 |
        |    7747 | 刘华建 | SHS407 |
        |    7745 | 汪琳    | SHS408 |
        |    7746 | 周舟    | SHS410 |
        |    7751 | 赵碧杉 | SHS411 |
        |    7748 | 黄晓菁 | SHS413 |
        |    7729 | 鞠乾翱 | SHS415 |
        |    7738 | 赵敏    | SHS418 |

         */

        $user_info = array(
                '7738'=>'SHS418',
        );
        $s_sql = "select
                  empl.EM_ID,empl.Name,empl.Code,empla.HRMS_UserField_1,empl.EMail,empl.Sex,empl.Telphone,empl.Mobile,empla.FEnglishName,
                  hminfo.EnterGroupDate,hminfo.InDueDate,empl.DimissionTime,empl.Status as onornot,hminfo.ProbationTerm,
                  empo.PositionName,empo.JobName,empo.UnitID,empo.UnitName,empo.BusinessGroupName,empo.CompanyName,empo.ServicePeriod,empo.EmployeeType,
                  emdi.Status,emdi.EnterDate,emdi.InDueDate,emdi.JobClassName,emdi.JobGrade,emdi.CompanyCode,emdi.DimissionType,emdi.FireType,
                  empl.IDCardID,empl.PastportNum,empl.Birthday,empl.NativePlace,empl.IDAddress,empl.NowWorkSpeciality,empl.MarriedStatus,empl.BankName,empl.BankAccountNum,
                  empla.NowResidence,
                  dinfo.Reason,
                  emcon.BeginDate,emcon.EndDate
                  from HM_Employees as empl
                  left join HM_EmployeesAddInfo as empla on empl.EM_ID=empla.EM_ID
                  left join HM_Em_WorkInfo as hminfo on empl.EM_ID = hminfo.EM_ID
                  left join v_Report_Workinfo as empo on empl.EM_ID = empo.EM_ID
                  left join v_Report_EmployeeDetailInfo as emdi on empl.EM_ID = emdi.EM_ID
                  left join V_Report_DimissionUnionFireInfo as dinfo on empl.EM_ID = dinfo.EM_ID
                  left join HM_EM_Contracts as emcon on empl.EM_ID = emcon.EM_ID";
        $result = mssql_query($s_sql);
        $data = array();
        $time = time();
        $i = 0;
        while( $row = mssql_fetch_assoc($result) ) {
            $code = trim($row['Code']);
            foreach($user_info as $user_id => $_code){
                if($_code == $code) {
                    //if($this->set_utf8($row['Status']) == "离职") {continue;}
                    $rs = array();
                    //$rs['kd_em_id'] = mssql_guid_string($row['EM_ID']);
                    //$rs['user_id'] = $user_id;
                   //if(empty($rs['user_id'])) {continue;}
                    $rs['user_name'] = $this->set_utf8($row['Name']);
                    $rs['real_name'] = $this->set_utf8($row['Name']);
                    $rs['sex']       = $row['Sex'];
                    $rs['identity_code'] = $this->_get_idcard_id($row['IDCardID'],$row['PastportNum']);//身份证或护照
                    $rs['identity_type'] = $this->_get_idcard_type($row['IDCardID'],$row['PastportNum']);//身份证或护照类型 1:身份证；2：护照
                    $rs['birthday'] = $this->_get_date($row['Birthday']);//获得生日  19601011
                    $rs['native_place'] = $this->set_utf8($row['NativePlace']);//籍贯
                    $rs['identity_address'] = $this->set_utf8($row['IDAddress']);//身份证地址
                    $rs['present_address'] = $this->set_utf8($row['NowResidence']);//现居地址
                    $rs['degree'] = $this->_get_degree_id($this->set_utf8($row['NowWorkSpeciality'])); //学位
                    $rs['graduate_time'] = ""; //毕业时间
                    $rs['graduate_university'] = ""; //毕业院校
                    $rs['profession'] = ""; //专业
                    $rs['marital_status'] = $this->set_utf8($row['MarriedStatus']); //婚姻状态 1:未婚 2：已婚
                    $rs['fertility_status'] = "";// 1:未生育 2：已生育
                    $rs['english_name'] = $row['FEnglishName'];
                    $rs['office_phone'] = $this->_get_phone($row['HRMS_UserField_1']);//公司电话号码
                    $rs['office_phone_ex'] = $this->_get_phone_ex($row['HRMS_UserField_1']);//电话及分机号
                    $rs['cellphone'] = empty($row['Mobile']) ? "0":$row['Mobile'];//手机
                    $rs['office_mail'] = empty($row['EMail']) ? "0":$row['EMail'];//邮箱
                    $rs['emergency_people'] = "";//紧急联系人
                    $rs['emergency_phone'] = "";//紧急联系电话
                    $rs['company_id'] = $this->_get_company_id($row['CompanyCode']);//签约公司

                    $rs['city_id']    = $this->_get_city_id($this->set_utf8($row['CompanyName']));//签约城市ID
                    $rs['work_city_id'] = $this->_get_city_id($this->set_utf8($row['CompanyName']));//工作城市ID
                    $rs['user_code']    = $row['Code'];//员工号
                    $rs['user_type']    = $this->_get_user_type($this->set_utf8($row['EmployeeType'])); //1:试用期员工,2:正式员工，3:实习生，4:兼职,5:临时工
                    $rs['job_status']   = "2";//1:在职，2：离职
                    $rs['leaving_type'] = $this->_get_leaving_type($this->set_utf8($row['DimissionType']),$this->set_utf8($row['FireType']));
                    $rs['reason_id'] = "";//金蝶的离职原因与现在的不符，故留空
                    $rs['other_reason'] = "";//其他离职原因
                    $rs['enter_date'] = $this->_get_date($row['EnterGroupDate']); //入职时间
                    $rs['indue_date'] = $this->_get_date($row['InDueDate']);//转正时间
                    $rs['leaving_date'] = $this->get_dimissionTime($row['onornot'],$row['DimissionTime']);//离职时间
                    $rs['last_date'] = $this->get_dimissionTime($row['onornot'],$row['DimissionTime']);//最后工作日
                    $rs['join_start'] = $this->_get_date($row['BeginDate']);//合同开始时间
                    $rs['join_end'] = $this->_get_date($row['EndDate']);//合同结束时间
                    $rs['join_keep'] = $this->_get_join_keep($row['BeginDate'],$row['EndDate']);//合同年限

                    $rs['trial_start'] = $this->_get_date($row['EnterGroupDate']);//试用期开始时间
                    $rs['trial_end']   = $this->_get_date($row['InDueDate']);//试用期结束时间
                    $rs['trial_keep']  = $row['ProbationTerm'];//试用期

                    $rs['bank_name']   = $this->set_utf8($row['BankName']);
                    $rs['bank_card']   = $row['BankAccountNum'];
                    $rs['p_level']   = $this->_get_p_level($row['JobClassName'],$row['JobGrade'],"P"); //获得p级
                    $rs['m_level']   = $this->_get_p_level($row['JobClassName'],$row['JobGrade'],"M"); //获得m级
                    $rs['new_train']   = "1";  //新员工是否培训
                    $rs['created']   = $time; //创建时间
                    $this->log("新增");
                    $i++;
                    echo $i;
                    var_dump($this->_update_data($rs,array('user_id'=>$user_id)));
                    unset($user_info[$user_id]);
                }
            }
        }
        return true;

    }


    public function insert_no_code_user() {
        /*
        |    4356 | 李振文      |      | 离职     |
        |    4363 | 姚遥         |      |            |
        |    4447 | 王怡杰      |      |            |
        |    4504 | 夏凡         |      |            |
        |    4800 | 王晓芸      |      |            |
        |    4850 | 杜阳         |      |            |
        |    5222 | 韩世伟      |      |            |
        |    5255 | 程斌         |      |            |
        |    5309 | 艾明杰      |      |            |
        |    5412 | 李少敏      |      | 离职     |
        |    5581 | 朱小冲      |      |            |
        |    6078 | 刘春燕      |      | 离职     |
        |    6118 | 高宇（BJ） |      |            |
        |    6217 | 范永红      |      |            |
        |    6326 | 郭丽娜      |      |            |
        |    6975 | 闫焕萱      |      |            |
        |    6986 | 王悦         |      |            |
        |    7042 | 李红         |      |            |
        */

        $user_info = array(
                "4356" => "李振文",
                "4363" => "姚遥",
                "4447" => "王怡杰",
                "4504" => "夏凡",
                "4800" => "王晓芸",
                "4850" => "杜阳",
                "5222" => "韩世伟",
                "5255" => "程斌",
                "5309" => "艾明杰",
                "5412" => "李少敏",
                "5581" => "朱小冲",
                "6078" => "刘春燕",
                "6118" => "高宇（BJ）",
                "6217" => "范永红",
                "6326" => "郭丽娜",
                "6975" => "闫焕萱",
                "6986" => "王悦",
                "7042" => "李红"
        );

        $s_sql = "select
                  empl.EM_ID,empl.Name,empl.Code,empla.HRMS_UserField_1,empl.EMail,empl.Sex,empl.Telphone,empl.Mobile,empla.FEnglishName,
                  hminfo.EnterGroupDate,hminfo.InDueDate,empl.DimissionTime,empl.Status as onornot,hminfo.ProbationTerm,
                  empo.PositionName,empo.JobName,empo.UnitID,empo.UnitName,empo.BusinessGroupName,empo.CompanyName,empo.ServicePeriod,empo.EmployeeType,
                  emdi.Status,emdi.EnterDate,emdi.InDueDate,emdi.JobClassName,emdi.JobGrade,emdi.CompanyCode,emdi.DimissionType,emdi.FireType,
                  empl.IDCardID,empl.PastportNum,empl.Birthday,empl.NativePlace,empl.IDAddress,empl.NowWorkSpeciality,empl.MarriedStatus,empl.BankName,empl.BankAccountNum,
                  empla.NowResidence,
                  dinfo.Reason,
                  emcon.BeginDate,emcon.EndDate
                  from HM_Employees as empl
                  left join HM_EmployeesAddInfo as empla on empl.EM_ID=empla.EM_ID
                  left join HM_Em_WorkInfo as hminfo on empl.EM_ID = hminfo.EM_ID
                  left join v_Report_Workinfo as empo on empl.EM_ID = empo.EM_ID
                  left join v_Report_EmployeeDetailInfo as emdi on empl.EM_ID = emdi.EM_ID
                  left join V_Report_DimissionUnionFireInfo as dinfo on empl.EM_ID = dinfo.EM_ID
                  left join HM_EM_Contracts as emcon on empl.EM_ID = emcon.EM_ID where empl.code is null";
        $result = mssql_query($s_sql);
        $data = array();
        $time = time();
        while( $row = mssql_fetch_assoc($result) ) {
            $_in_time = trim($row['EnterGroupDate']);
            $_in_time = strtotime($_in_time);
            if($_in_time >= $this->filter_time) {continue;}
            $name = trim($this->set_utf8($row['Name']));
            foreach($user_info as $user_id => $uname){
                if($name == $uname) {
                    //if($this->set_utf8($row['Status']) == "离职") {continue;}
                    $rs = array();
                    //$rs['kd_em_id'] = mssql_guid_string($row['EM_ID']);
                    //$rs['user_id'] = $user_id;
                    if(empty($rs['user_id'])) {continue;}
                    $rs['user_name'] = $this->set_utf8($row['Name']);
                    $rs['real_name'] = $this->set_utf8($row['Name']);
                    $rs['sex']       = $row['Sex'];
                    $rs['identity_code'] = $this->_get_idcard_id($row['IDCardID'],$row['PastportNum']);//身份证或护照
                    $rs['identity_type'] = $this->_get_idcard_type($row['IDCardID'],$row['PastportNum']);//身份证或护照类型 1:身份证；2：护照
                    $rs['birthday'] = $this->_get_date($row['Birthday']);//获得生日  19601011
                    $rs['native_place'] = $this->set_utf8($row['NativePlace']);//籍贯
                    $rs['identity_address'] = $this->set_utf8($row['IDAddress']);//身份证地址
                    $rs['present_address'] = $this->set_utf8($row['NowResidence']);//现居地址
                    $rs['degree'] = $this->_get_degree_id($this->set_utf8($row['NowWorkSpeciality'])); //学位
                    $rs['graduate_time'] = ""; //毕业时间
                    $rs['graduate_university'] = ""; //毕业院校
                    $rs['profession'] = ""; //专业
                    $rs['marital_status'] = $this->set_utf8($row['MarriedStatus']); //婚姻状态 1:未婚 2：已婚
                    $rs['fertility_status'] = "";// 1:未生育 2：已生育
                    $rs['english_name'] = $row['FEnglishName'];
                    $rs['office_phone'] = $this->_get_phone($row['HRMS_UserField_1']);//公司电话号码
                    $rs['office_phone_ex'] = $this->_get_phone_ex($row['HRMS_UserField_1']);//电话及分机号
                    $rs['cellphone'] = empty($row['Mobile']) ? "0":$row['Mobile'];//手机
                    $rs['office_mail'] = empty($row['EMail']) ? "0":$row['EMail'];//邮箱
                    $rs['emergency_people'] = "";//紧急联系人
                    $rs['emergency_phone'] = "";//紧急联系电话
                    $rs['company_id'] = $this->_get_company_id($row['CompanyCode']);//签约公司

                    $rs['city_id']    = $this->_get_city_id($this->set_utf8($row['CompanyName']));//签约城市ID
                    $rs['work_city_id'] = $this->_get_city_id($this->set_utf8($row['CompanyName']));//工作城市ID
                    $rs['user_code']    = "";
                    $rs['user_type']    = $this->_get_user_type($this->set_utf8($row['EmployeeType'])); //1:试用期员工,2:正式员工，3:实习生，4:兼职,5:临时工
                    $rs['job_status']   = "2";//1:在职，2：离职
                    $rs['leaving_type'] = $this->_get_leaving_type($this->set_utf8($row['DimissionType']),$this->set_utf8($row['FireType']));
                    $rs['reason_id'] = "";//金蝶的离职原因与现在的不符，故留空
                    $rs['other_reason'] = "";//其他离职原因
                    $rs['enter_date'] = $this->_get_date($row['EnterGroupDate']); //入职时间
                    $rs['indue_date'] = $this->_get_date($row['InDueDate']);//转正时间
                    $rs['leaving_date'] = $this->get_dimissionTime($row['onornot'],$row['DimissionTime']);//离职时间
                    $rs['last_date'] = $this->get_dimissionTime($row['onornot'],$row['DimissionTime']);//最后工作日
                    $rs['join_start'] = $this->_get_date($row['BeginDate']);//合同开始时间
                    $rs['join_end'] = $this->_get_date($row['EndDate']);//合同结束时间
                    $rs['join_keep'] = $this->_get_join_keep($row['BeginDate'],$row['EndDate']);//合同年限

                    $rs['trial_start'] = $this->_get_date($row['EnterGroupDate']);//试用期开始时间
                    $rs['trial_end']   = $this->_get_date($row['InDueDate']);//试用期结束时间
                    $rs['trial_keep']  = $row['ProbationTerm'];//试用期

                    $rs['bank_name']   = $this->set_utf8($row['BankName']);
                    $rs['bank_card']   = $row['BankAccountNum'];
                    $rs['p_level']   = $this->_get_p_level($row['JobClassName'],$row['JobGrade'],"P"); //获得p级
                    $rs['m_level']   = $this->_get_p_level($row['JobClassName'],$row['JobGrade'],"M"); //获得m级
                    $rs['new_train']   = "1";  //新员工是否培训
                    $rs['created']   = $time; //创建时间
                    $this->log("新增");
                    var_dump($this->_update_data($rs,array('user_id'=>$user_id)));
                    unset($user_info[$user_id]);
                }
            }
            }
            return true;
    }

    private function get_dimissionTime($onornot,$DimissionTime) {
        $time = $onornot == 2 ? strtotime($DimissionTime):0;
        if($time) {
            return date("Ymd",$time);
        }
        return '0';
    }

    private function _get_last_work($code,$time) {
        $code = trim($code);
        $time = trim($time);
        if(empty($code) || empty($time)) {
            return "";
        }

        $s_sql = "SELECT * FROM access_all_record WHERE CODE = '{$code}' ORDER BY id DESC LIMIT 1";
        $rs = $this->get_db_row($s_sql,$this->oa_readdb);
        return $rs['access_date'];
    }

    public function _insert_data($info) {
        return $this->_insert($info,"user");
    }

    public function _update_data($info,$where) {
        return $this->_update($info,"user",$where);
    }

    private function _get_phone($phone) {
        $phone = trim($phone);
        if(empty($phone)) {return "";}
        $rs = explode("-",$phone);
        if(empty($rs[2]) && strlen($rs[1]) >4) {
            return $phone;
        }else {
            if(!empty($rs[1]) && strlen($rs[1]) <=4) {
                return $rs[0];
            }else {
                if($rs[1]) {
                    return $rs[0]."-".$rs[1];
                }else {
                    return $rs[0];
                }

            }
        }
        return "";
    }

    private function _get_phone_ex($phone) {
        $phone = trim($phone);
        if(empty($phone)) {return "0";}
        $rs = explode("-",$phone);
        if(!empty($rs[2])) {
            return intval($rs[2]);
        }elseif(!empty($rs[1]) && strlen($rs[1]) <=4) {
            return $rs[1];
        }
        return "0";
    }

    private function _get_company_id($company_code) {
        $company_code = trim($company_code);
        if(empty($company_code)) {return 0;}
        $codes = explode(".",$company_code);
        if("KD01.0001" == $codes[0].".".$codes[1]) {
            return "1";
        }else if("KD01.0002" == $codes[0].".".$codes[1]){
            return "2";
        }else {return 0;}
    }

    private function _update ($data = array(),$tablename = "",$where = array(),$status = FALSE) {
        if(empty($tablename)) {
            return false;
        }
        $data_count  = count($data);
        if ($data_count < 1) {
            return false;
        }
        if (empty($where)) {
            return false;
        }
        //防止误更新
        if (is_numeric($where)) {
            return false;
        }
        $sql = "UPDATE " . $tablename . " SET ";
        $i = 1;
        foreach ($data as $key => $value) {
            if(empty($value) && $value!==0) {continue;}
            $v = self::escape_value($value);
            $sql .= $status ? "`{$key}`= $v ":"`{$key}` = '{$v}'";
            $sql .= ($i < $data_count)?',':'';
            $i ++;
        }

        $s = substr($sql,strlen($sql)-1,1);
        if($s == ",") {
            $sql = substr($sql,0,strlen($sql)-1);
        }
        $_where = $this->build_where($where);
        $sql .= @$_where['where'];
        return $this->execute($sql, $_where['params'], $this->writedb);
    }

    private function build_where ($where) {
        $_where = array('where' => '', 'params' => array());
        if (empty($where)) {
            return $_where;
        }
        if (is_array($where) && count($where)) {
            foreach ($where as $key => $value) {
                if (preg_match("/\?/", $key)) {
                    $_where['field'][] = '(' . $key . ')';
                } else {
                    $_where['field'][] = '(`' . $key . '` = ?)';
                }
                $_where['params'][] = self::escape_value($value);
            }
            $_where['where']=' WHERE ' . implode(' AND ',$_where['field']);
        }else{
            $_where['where']=' WHERE ' . $where;
        }
        return $_where;
    }

    public static function escape_value ($value) {
        if (is_numeric($value) || is_string($value)) {
            return str_replace(array("'",'\\'),array("''",'\\\\'),$value);
        } else {
            return $value;
        }
    }

    private function _insert($arr,$tablename) {
        if(empty($tablename)) {return false;}
        $param = array();
        $values = array();
        foreach($arr as $k => $v) {
            if(empty($v) && $v!==0) {
                unset($arr[$k]);
                continue;
            }
            $values[] = "?";
            $param[] = $v;

        }
        $sql = "INSERT INTO " . $tablename . " (`";
        $sql .= implode('`,`', array_keys($arr));
        $sql .= "`) VALUES (";
        $sql .= implode(",", $values) . ")";
print_r($param);
        //$sql = "INSERT INTO user (`user_name`,`real_name`,`sex`,`identity_code`,`identity_type`,`birthday`,`native_place`,`identity_address`,`present_address`,`degree`,`graduate_time`,`graduate_university`,`profession`,`marital_status`,`fertility_status`,`english_name`,`office_phone`,`office_phone_ex`,`cellphone`,`office_mail`,`emergency_people`,`emergency_phone`,`company_id`,`city_id`,`work_city_id`,`user_code`,`user_type`,`job_status`,`leaving_type`,`reason_id`,`other_reason`,`enter_date`,`indue_date`,`leaving_date`,`last_date`,`join_start`,`join_end`,`join_keep`,`trial_start`,`trial_end`,`trial_keep`,`bank_name`,`bank_card`,`p_level`,`m_level`,`new_train`,`created`) VALUES ('0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0')";


        $rs = $this->execute($sql, $param, $this->writedb);
        return $rs;
    }

    private function _get_degree_id($type) {
        $type = trim($type);
        if(empty($type)) {return 0;}
        //1:高中及以下;2:专科;3:本科;4:硕士;5:博士
        $array[1] = array("高中");
        $array[2] = array("专科","职高","大专","中技","中专");
        $array[3] = array("本科");
        $array[4] = array("硕士","研究生");
        $array[5] = array("博士");
        foreach($array as $k => $v) {
            if(in_array($type,$v)) {
                return $k;
            }
        }
        return 1;
    }

    //获得职位等级
    private function _get_p_level($JobClassName,$JobGrade,$type) {
        if(empty($JobClassName)) {return 0;}
        $_type = substr($JobClassName,0,1);
        if($_type == $type) {
            return $JobGrade;
        }else {return 0;}
    }

    //获得合同年限,单位：年
    private function _get_join_keep($BeginDate,$EndDate) {
        if(empty($BeginDate) || empty($EndDate)) {return 0;}
        $begin_y = intval(date("Y",strtotime($BeginDate)));
        $end_y = intval(date("Y",strtotime($EndDate)));
        $y = $end_y-$begin_y;
        return $y;
    }

    private function _get_leaving_type($type1,$type2) {
        if(empty($type1) && empty($type2)) {
            return 0;
        }
        if(!empty($type1)) {
            return 1;//主动离职
        }else{
            return 2;//辞退
        }
    }
    private function _get_reason_id($type) {
        $type = trim($type);
        //1:主动离职，2：被动离职(公司淘汰)，3：未来报道
        //离职原因（公司淘汰，解除合同，终止合同，自谋职业，自我淘汰）
        $a = array("公司淘汰");
        $b = array("自谋职业","终止合同","解除合同","自我淘汰");
        if(in_array($type,$a)) {
            return 2;
        }else if(in_array($type,$b)){
            return 1;
        }else {
            return 0;
        }
        $array[1] = "公司淘汰";
    }


    private function _get_job_status($type,$time) {
        //1:在职，2：离职
        $type = trim($type);
        $time = trim($time);
        if($type != "离职" && $time=='0000-00-00 00:00:00') {return "1";}else{return "2";}
    }

    private function _get_user_type($type) {
        //1:试用期员工,2:正式员工，3:实习生，4:兼职,5:临时工
        $array[1] = "试用员工";
        $array[2] = "正式员工";
        $array[3] = "实习员工";
        $array[4] = "兼职";
        $array[5] = "临时工";

        $type = trim($type);
        foreach($array as $k => $v) {
            if($type == $v) {
                return $k;
            }
        }
        return 1;
    }

    private function _get_city_id($city_name) {
        $city_name = trim($city_name);
        if(empty($city_name)) {
            return 0;
        }
        return $this->citie[$city_name];
    }

    private function _get_date($data) {
        $data = trim($data);
        if(empty($data) || "0000-00-00 00:00:00" == $data) {
            return 0;
        }
        $data = strtotime($data);
        return date("Ymd",$data);
    }

    private function _get_idcard_id($IDCardID,$PastportNum) {
        if(empty($IDCardID) && empty($PastportNum)) {
            return 0;
        }else if(empty($IDCardID)) {
            return $PastportNum;
        }else {
            return $IDCardID;
        }
    }

    private function _get_idcard_type($IDCardID,$PastportNum) {
        if(empty($IDCardID) && empty($PastportNum)) {
            return 1;
        }else if(empty($IDCardID)) {
            return 2;
        }else{return 1;}
    }

    public function set_utf8($str) {
        $origin = mb_detect_encoding($str,array('CP936','UTF-8','ASCII','GBK','GB2312'));
        return mb_convert_encoding($str,'UTF-8',$origin);
    }

    /**
     * 清空数据库
     * @param unknown_type $db_name
     */
    private function clear_db($db_name){
        $sql = "delete from $db_name";
        echo $sql;
        return $this->execute($sql,array(),$this->writedb);
    }

    /**
     * 重置自增id
     * @param unknown_type $db_name
     */
    private function alter_db($db_name){
        $sql = "alter table $db_name AUTO_INCREMENT=1";
        return $this->execute($sql,array(),$this->writedb);
    }

    public function db_connect() {
        $dbhost = "192.168.1.60";
        $dbusname = "sa";
        $dbpasswd = "sa";
        $dbname = "AIS20100415101750";
        $conn = mssql_connect(
            $dbhost,
            $dbusname,
            $dbpasswd
        );
        mssql_select_db($dbname,$conn);
    }
}
